package Chinese.Education.Identify.service;

import Chinese.Education.Identify.pojo.ScanResult;
import Chinese.Education.Identify.mapper.ScanResultMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class VulnerabilityScanService {

    @Value("${scanner.api.url}")
    private String scannerApiUrl;

    @Value("${scanner.api.key}")
    private String apiKey;

    @Resource
    private ScanResultMapper scanResultMapper;

    /**
     * 启动远程扫描任务
     * @param target 扫描目标
     * @param scanName 扫描任务名称
     * @return 扫描任务ID
     */
    public Map<String, Object> startRemoteScan(String target, String scanName) {
        try {
            // 生成模拟的扫描任务ID
            String taskId = "task_" + System.currentTimeMillis();

            // 保存扫描任务到数据库
            ScanResult scanResult = new ScanResult();
            scanResult.setScanName(scanName);
            scanResult.setTarget(target);
            scanResult.setStartTime(new Date().toString());
            scanResult.setStatus("进行中");
            scanResult.setDescription("模拟扫描任务ID: " + taskId);
            scanResultMapper.insertScanResult(scanResult);

            // 模拟异步完成任务
            new Thread(() -> {
                try {
                    // 模拟扫描过程，等待5秒
                    Thread.sleep(5000);

                    // 更新扫描结果为已完成
                    ScanResult result = new ScanResult();
                    result.setId(scanResult.getId());
                    result.setScanName(scanName);
                    result.setTarget(target);
                    result.setStartTime(scanResult.getStartTime());
                    result.setEndTime(new Date().toString());
                    result.setStatus("已完成");
                    result.setDescription("模拟扫描完成。发现0个高危漏洞，2个中危漏洞。");
                    scanResultMapper.updateScanResult(result);
                } catch (InterruptedException e) {
                    e.printStackTrace();

                    // 如果出现异常，更新状态为已取消
                    try {
                        ScanResult result = new ScanResult();
                        result.setId(scanResult.getId());
                        result.setScanName(scanName);
                        result.setTarget(target);
                        result.setStartTime(scanResult.getStartTime());
                        result.setEndTime(new Date().toString());
                        result.setStatus("已取消");
                        result.setDescription("模拟扫描被中断: " + e.getMessage());
                        scanResultMapper.updateScanResult(result);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }).start();

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("taskId", taskId);
            result.put("message", "扫描任务已启动");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "启动扫描任务异常: " + e.getMessage());
            return result;
        }
    }

    /**
     * 获取扫描任务状态
     * @param taskId 任务ID
     * @return 任务状态
     */
    public Map<String, Object> getScanStatus(String taskId) {
        try {
            // 从数据库中获取扫描结果 (修复方法名)
            ScanResult scanResult = scanResultMapper.selectScanResultById(Integer.parseInt(taskId.split("_")[1]));

            if (scanResult != null) {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 200);
                result.put("status", scanResult.getStatus());
                result.put("taskId", taskId);
                return result;
            } else {
                Map<String, Object> result = new HashMap<>();
                result.put("code", 404);
                result.put("message", "未找到扫描任务");
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "获取扫描状态异常: " + e.getMessage());
            return result;
        }
    }

    /**
     * 获取扫描报告
     * @param taskId 任务ID
     * @return 扫描报告
     */
    public Map<String, Object> getScanReport(String taskId) {
        try {
            // 构造模拟报告
            StringBuilder report = new StringBuilder();
            report.append("扫描报告\n");
            report.append("========\n\n");
            report.append("扫描名称: 示例扫描任务\n");
            report.append("扫描目标: 192.168.1.1\n");
            report.append("开始时间: 2025-08-21 10:00:00\n");
            report.append("结束时间: 2025-08-21 10:05:00\n");
            report.append("状态: 已完成\n\n");
            report.append("发现的漏洞:\n");
            report.append("----------\n");
            report.append("1. 中危漏洞: 弱密码策略 (CVSS: 5.0)\n");
            report.append("2. 中危漏洞: 信息泄露 (CVSS: 4.3)\n");
            report.append("\n建议:\n");
            report.append("-----\n");
            report.append("1. 加强密码策略，使用复杂密码\n");
            report.append("2. 限制敏感信息的暴露\n");

            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("report", report.toString());
            result.put("taskId", taskId);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<>();
            result.put("code", 500);
            result.put("message", "获取扫描报告异常: " + e.getMessage());
            return result;
        }
    }

    /**
     * 解析响应获取任务ID
     * @param response 响应内容
     * @return 任务ID
     */
    private String parseTaskIdFromResponse(String response) {
        // 这里需要根据实际API响应格式进行解析
        // 假设响应为 {"id": "task123", ...}
        // 简单示例，实际应使用JSON解析库
        if (response.contains("\"id\":")) {
            int start = response.indexOf("\"id\":\"") + 6;
            int end = response.indexOf("\"", start);
            return response.substring(start, end);
        }
        return "unknown";
    }

    /**
     * 解析响应获取状态
     * @param response 响应内容
     * @return 状态
     */
    private String parseStatusFromResponse(String response) {
        // 这里需要根据实际API响应格式进行解析
        // 假设响应为 {"status": "completed", ...}
        if (response.contains("\"status\":")) {
            int start = response.indexOf("\"status\":\"") + 10;
            int end = response.indexOf("\"", start);
            return response.substring(start, end);
        }
        return "unknown";
    }

    /**
     * 根据扫描报告更新数据库中的扫描结果
     * @param taskId 任务ID
     * @param report 报告内容
     */
    private void updateScanResultWithReport(String taskId, String report) {
        // 根据任务ID查找并更新扫描结果
        // 这里需要根据实际情况实现
        // 例如：更新状态为"已完成"，设置结束时间等
    }
    public Map<String, Object> selectScanResult(int page, int limit, String scanName, int id) {
        int offset = (page - 1) * limit;
        List<ScanResult> scanResults = scanResultMapper.selectScanResult(limit, offset, scanName, id);
        int count = scanResultMapper.selectCount();
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("msg", "");
        result.put("count", count);
        result.put("data", scanResults);
        return result;
    }


}
